<template>
	<view class="page">
		<image class="upload-icon" :src="imageUrl || '/static/images/UploadSmall@2x.png'" @click.prevent="chooseImage()">
		</image>
		<textarea class="content" v-model="caseContent" maxlength="-1" placeholder="请输入详细案例"></textarea>
		<view class="btn" @click.prevent="submit()">{{id ? '修改案例' : '添加案例'}}</view>
	</view>
</template>

<script>
	import {
		requestAddExample,
		requestUpdateExample,
		uploadFile
	} from '@/apis/request.js';

	export default {
		data() {
			return {
				id: '',
				caseContent: '',
				imageUrl: ''
			};
		},
		onLoad(options) {
			console.log('案例参数', options);
			if (options.data) {
				const data = JSON.parse(options.data);
				this.id = data.id;
				this.imageUrl = data.image;
				this.caseContent = data.caseContent;
			}
		},
		methods: {
			//上传图片
			chooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						uploadFile(res.tempFilePaths[0]).then(res => {
							this.imageUrl = res;
						});
					}
				});
			},
			submit() {
				if (!this.imageUrl) {
					this.$Toast('请上传案例图片');
					return
				}
				if (!this.caseContent) {
					this.$Toast('请输入案例描述');
					return
				}
				if (this.id) {
					requestUpdateExample({
						id: this.id,
						caseContent: this.caseContent,
						image: this.imageUrl
					}).then(res => {
						uni.navigateBack();
					});
				} else {
					requestAddExample({
						caseContent: this.caseContent,
						image: this.imageUrl
					}).then(res => {
						uni.navigateBack();
					});
				}
			}
		}
	};
</script>

<style scoped lang="scss">
	.page {
		background-color: #FFFFFF;
		height: 100%;
		min-height: 100vh;

		.upload-icon {
			margin-left: 34rpx;
			width: 205rpx;
			height: 205rpx;
			border-radius: 10rpx;
		}

		.content {
			margin: 20rpx 30rpx;
			width: calc(100% - 100rpx);
			padding: 20rpx;
			min-height: 300rpx;
			background: #F5F7F8;
			border-radius: 10rpx;
		}

		.btn {
			margin: 20rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			font-size: 30rpx;
			color: #FFFFFF;
			background-color: $uni-color-primary;
		}
	}
</style>